package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.AppConfig;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.MainLinGanAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;

public class SearchResultActivity extends BaseActivity {
	private EditText input;
	
	private PullToRefreshListView mPullToRefreshView;
	private ListView listView;
	private MainLinGanAdapter adapter;
	private List<JSONObject> listItems = new ArrayList<JSONObject>();
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter.notifyDataSetChanged();
				mPullToRefreshView.onRefreshComplete();
				if(pageEnd)mPullToRefreshView.setMode(Mode.PULL_FROM_START);
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setVisibility(View.GONE);
		rightLay.setOnClickListener(this);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setText("取消");
		
//		hisStr = AppConfig.getAppConfig(this).get("search_his");
//		hisList = new LinkedList<String>();
//		if(!StringUtil.isEmpty(hisStr)){
//			String[] arr = hisStr.split("###");
//			for (String str : arr) {
//				hisList.add(str);
//			}
//		}
		
		
		input = (AutoCompleteTextView)findViewById(R.id.content_header_center_edit);
		input.setImeOptions(EditorInfo.IME_ACTION_SEARCH);  
		input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)){
					String instr = input.getText().toString();
					if(StringUtil.isEmpty(instr)){
						UIUtil.ToastMessage(activity, "搜索内容为空！");
						return false;
					}
					UIUtil.hideSoftInputFromWindow(input, activity);
					if(urlParam==null)urlParam = new HashMap<String,String>();
					urlParam.put("k", instr);
					clearData();
					loadData(urlParam);
//					Intent intent = new Intent();
//					intent.putExtra("data", map);
//					activity.setResult(Activity.RESULT_OK,intent);
//					activity.finish();
					return true;
				}
				return false;
			}
		});
		
//		history = (RelativeLayout) findViewById(R.id.search_history);
//		hot = (RelativeLayout) findViewById(R.id.search_hot);
//		
//		historyItems = new LinkedList<String>();
//		hotItems = new LinkedList<String>();
//		
//		loadData(null);
		
		mPullToRefreshView = (PullToRefreshListView) findViewById(R.id.search_result_listview);
		mPullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if(PullToRefreshBase.Mode.PULL_FROM_START == mPullToRefreshView.getCurrentMode()){
					String label = DateUtils.formatDateTime(appContext,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
					mPullToRefreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					clearData();
					loadData(urlParam);
				}else if(PullToRefreshBase.Mode.PULL_FROM_END == mPullToRefreshView.getCurrentMode()){
					if(urlParam==null)urlParam = new HashMap<String,String>();
					pageIndex++;
					urlParam.put("page", String.valueOf(pageIndex));
					loadData(urlParam);
				}
			}
		});
		listView = mPullToRefreshView.getRefreshableView();
		//listView.setDividerHeight(UIUtil.dip2px(appContext, 10));
		adapter = new MainLinGanAdapter(activity, null, listItems, 2);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Bundle data  = new Bundle();
				data.putString("url", BaseTools.getFrom("embed_url", listItems.get(new Long(id).intValue())));
				data.putString("id", BaseTools.getFrom("_id", listItems.get(new Long(id).intValue())));
				UIUtil.openActivity(activity, WorkDetailActivity.class, data);
			}
		});
		
		@SuppressWarnings("unchecked")
		Map<String,String> map = (Map<String,String>) getIntent().getSerializableExtra("data");
//		if(map!=null&&map.size()>0&&!StringUtil.isEmpty(map.get("key"))){
//			String hisStr = AppConfig.getAppConfig(activity).get("search_his");
//			int i=0;
//			while(!StringUtil.isEmpty(hisStr)&&i<hisStr.split("###").length){
//				if(hisStr.split("###")[i].equals(map.get("key")))break;
//			}
//			if(StringUtil.isEmpty(hisStr)||i>=hisStr.split("###").length){
//				hisStr = StringUtil.isEmpty(hisStr)?map.get("key"):hisStr+"###"+map.get("key");
//				while(!StringUtil.isEmpty(hisStr)&&hisStr.split("###").length>10){
//					hisStr = hisStr.substring(hisStr.indexOf("###")+"###".length());
//				}
//				AppConfig.getAppConfig(activity).set("search_his",hisStr);
//			}
//		}
		input.setText(map.get("key"));
		if(urlParam==null)urlParam = new HashMap<String,String>();
		urlParam.clear();
		urlParam.put("page", String.valueOf(0));
		urlParam.put("k",map.get("key"));
		listItems.clear();
		loadData(urlParam);
		
		
		
		//loadData(null);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==2&&resultCode==Activity.RESULT_OK&&null!=data){
			String tid = data.getStringExtra("id");
			if(!StringUtil.isEmpty(tid)){
				for (int i = 0; i < listItems.size(); i++) {
					if(BaseTools.getFrom("_id", listItems.get(i)).equals(tid)){
						try {
							int con = Integer.parseInt(BaseTools.getFrom("statistic.COMMENT", listItems.get(i)));
							con++;
							listItems.get(i).getJSONObject("statistic").put("COMMENT", con);
							adapter.notifyDataSetChanged();
						} catch (Exception e) {
						}
						break;
					}
				}
			}
		}
	}

	@Override
	public void loadData(Map<String, String> param) {
		if(param==null)param = new HashMap<String, String>();
		String hisStr = AppConfig.getAppConfig(activity).get("search_his");
		
		int i=0;
		while(!StringUtil.isEmpty(hisStr)&&i<hisStr.split("###").length){
			if(hisStr.split("###")[i].equals(param.get("k")))break;
			i++;
		}
		if(StringUtil.isEmpty(hisStr)||i>=hisStr.split("###").length){
			hisStr = StringUtil.isEmpty(hisStr)?param.get("k"):hisStr+"###"+param.get("k");
			while(!StringUtil.isEmpty(hisStr)&&hisStr.split("###").length>10){
				hisStr = hisStr.substring(hisStr.indexOf("###")+"###".length());
			}
			AppConfig.getAppConfig(activity).set("search_his",hisStr);
		}
		
		param.put("province_city", appContext.cityId);
		HttpService.postByText(URLs.MAIN_LINGGAN_SEARCH, param, new TextHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
				try {
					if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
					JSONObject result = new JSONObject(resultStr);
					if(result.getInt("status")==0){
						JSONArray data = result.getJSONArray("data");
						for (int i = 0; data!=null && i < data.length(); i++) {
							listItems.add(data.getJSONObject(i));
						}
						if(data==null||data.length()<=0){
							pageEnd = true;
							adapter.setPageEnd(pageEnd);
						}
					}else{
						if(pageIndex>0)pageIndex--;
					}
					mHandler.sendEmptyMessage(1);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				//if(BuildConfig.DEBUG)Log.e("==onFailure==", arg2);
				UIUtil.ToastMessage(activity, "抱歉，访问失败");
			}
		});
	}

	@Override
	public void clearData() {
		pageEnd = false;
		if(urlParam==null)urlParam = new HashMap<String,String>();
		pageIndex=0;
		urlParam.put("page", String.valueOf(pageIndex));
		adapter.setPageEnd(pageEnd);
		mPullToRefreshView.setMode(Mode.BOTH);
		listItems.clear();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_right_lay:
			finish();
			break;
		default:
			break;
		}
	}

}
